from lxml import etree
from lxml.etree import XMLSyntaxError

def parse_xml_to_dict(xml_str:str)->dict:
    """
    将xml字符串解析成字典形式，参考tensorflow的recursive_parse_xml_to_dict
    Args:
        xml_str: xml字符串

    Returns:
        如果格式错误，返回None。
        Python dictionary holding XML contents.
    """
    try:
        xml = etree.fromstring(xml_str)
        return __parse_xml_to_dict(xml)
    except XMLSyntaxError as e:
        return None

def __parse_xml_to_dict(xml):
    if len(xml) == 0:  # 遍历到底层，直接返回tag对应的信息
        return {xml.tag: xml.text}

    result = {}
    for child in xml:
        child_result = __parse_xml_to_dict(child)  # 递归遍历标签信息
        if child.tag != 'object':
            result[child.tag] = child_result[child.tag]
        else:
            if child.tag not in result:  # 因为object可能有多个，所以需要放入列表里
                result[child.tag] = []
            result[child.tag].append(child_result[child.tag])
    return {xml.tag: result}
